import React, { Component } from 'react'
import Info from "components/info";
import { Button, Form, Input, Select, Modal, Row, Col, InputNumber, message, Table } from "antd";
import periodDefineService from 'containers/finance-setting/period-define/period-define.service'
import SlideFrame from "components/slide-frame";
import PeriodDefineRule from "./period-define-rule";
import Condition from "components/condition";
import { deepFullCopy, messages } from "share/common";
import 'styles/finance-setting/account-period-define/new-account-rule.scss'
import Space from "components/space"

class PeriodDefineDetail extends Component{

  attributes = [
    { title: messages('finance-5.key1')/*会计期编码*/, dataIndex: 'periodSetCode' },
    { title: messages('finance-5.key2')/*会计期名称*/, dataIndex: 'periodSetName' },
    { title: messages('finance-5.key3')/*期间总数*/, dataIndex: 'totalPeriodNum' },
    { title: messages('finance-5.key4')/*名称附加*/, dataIndex: 'periodAdditionalFlag',
      render: value => value === 'P' ? messages('finance-5.key5')/*附加前缀*/ : messages('finance-5.key6')/*附加后缀*/ }
  ];

  state = {
    info: {},
    infoLoading: false,
    saveLoading: false,
    tableLoading: false,
    data: [],
    isDefined: false,
    yearFrom: null,
    yearTo: null
  };

  columns = [
    {
      title: messages('common.sequence')/*序号*/, dataIndex: 'periodNum',
      newRender: (value, record, index) => { return {
        ele: <Input className="no-input-style" disabled/>,
        initialValue: index + 1
      } }
    },
    {
      title: messages('finance-5.key7')/*期间名附加*/, dataIndex: 'periodAdditionalName',
      newRender: (value, record, index) => {
        const { data } = this.state;
        return {
          ele: <Input placeholder={messages('common.please.input')/*请输入*/} onChange={e =>{
            data[index].periodAdditionalName = e.target.value;
            this.setState({ data });
          }}/>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key8')/*月份从*/, dataIndex: 'monthFrom',
      newRender: (value, record, index) => {
        const { data, info } = this.state;
        let options = this.getOption(1, record.monthTo || 12);
        return {
          ele: <Select
            placeholder={messages('common.select')/*请选择*/}
            disabled={index !== data.length - 1 || index === info.totalPeriodNum - 1}
            onChange={key => {
              data[index].monthFrom = Number(key);
              this.setState({ data });
            }}
          >
            {options}
          </Select>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key9')/*日期从*/, dataIndex: 'dateFrom',
      newRender: (value, record, index) => {
        const { data, info } = this.state, { monthFrom = 0, monthTo = 0, dateTo = 0 } = data[index];
        let max = monthFrom ? this.getMonthDay(monthFrom) : 0;
        if (monthFrom === monthTo && dateTo) {
          max = dateTo;
        }
        let options = this.getOption(1, max);
        return {
          ele: <Select
            placeholder={messages('common.select')/*请选择*/}
            disabled={index !== data.length - 1 || index === info.totalPeriodNum - 1}
            onChange={key => {
              data[index].dateFrom = Number(key);
              this.setState({ data });
            }}
          >
            {options}
          </Select>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key10')/*月份到*/, dataIndex: 'monthTo',
      newRender: (value, record, index) => {
        let { data } = this.state, { monthFrom = 0, dateFrom = 0, dateTo = 0 } = record;
        const originMonthFrom = data[0].monthFrom || 0, originDateFrom = data[0].dateFrom || 0;
        let options = [];
        if (dateFrom) {
          if (index === 0) {
            options = this.getOption(monthFrom, 12).concat(this.getOption(1,monthFrom, false));
          } else {
            if (originMonthFrom > monthFrom) {
              options = this.getOption(monthFrom, originMonthFrom, originDateFrom !== 1 && originDateFrom > dateTo);
            } else if (originMonthFrom < monthFrom) {
              options = this.getOption(monthFrom, 12).concat(this.getOption(1, originMonthFrom, originDateFrom !== 1 && originDateFrom > dateTo));
            } else {
              if (dateFrom > originDateFrom) {
                options = this.getOption(monthFrom, 12).concat(this.getOption(1, originMonthFrom, false));
              } else {
                options = this.getOption(monthFrom, monthFrom);
              }
            }
          }
        }
        return {
          ele: <Select
            placeholder={messages('common.select')/*请选择*/}
            onChange={key => {
              let keyNum = Number(key);
              data[index].monthTo = keyNum;
              if (dateTo) {
                let temp = { index: index + 1, monthTo: undefined, dateTo: undefined };
                if (dateTo === this.getMonthDay(key)) {
                  temp.monthFrom = keyNum + 1 > 12 ? 1 : keyNum + 1;
                  temp.dateFrom = 1;
                } else {
                  temp.monthFrom = keyNum;
                  temp.dateFrom = dateTo + 1;
                }
                data.map(item => {
                  if (item.index === index + 1) {
                    item = Object.assign(item, temp);
                  }
                  return item;
                });
                data.splice(index + 2, data.length - index - 2);
              }
              this.props.form.resetFields();
              this.setState({ data });
            }}
          >
            {options}
          </Select>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key11')/*日期到*/, dataIndex: 'dateTo',
      newRender: (value, record, index) => {
        let { data, info } = this.state, { monthFrom = 0, dateFrom = 0, monthTo = 0 } = record;
        const originMonthFrom = data[0].monthFrom || 0, originDateFrom = data[0].dateFrom || 0;
        let max = monthTo ? this.getMonthDay(monthTo) : 0;
        let options = [];
        if (monthTo) {
          options = this.getOption(dateFrom, max);
          if (monthTo !== originMonthFrom) {
            options = this.getOption(monthTo === monthFrom ? dateFrom : 1, max);
          } else {
            if (monthTo === monthFrom) {
              if (dateFrom > originDateFrom) {
                options = this.getOption(dateFrom, max);
              } else if (dateFrom < originDateFrom) {
                options = this.getOption(dateFrom, originDateFrom, false);
              } else {
                options = this.getOption(dateFrom, max).concat(this.getOption(1, dateFrom, false));
              }
            } else {
              options = this.getOption(1, originDateFrom, false);
            }
          }
        }
        return {
          ele: <Select
            placeholder={messages('common.select')/*请选择*/}
            onChange={key => {
              let keyNum = Number(key);
              data[index].dateTo = keyNum;
              let temp = { index: index + 1, monthTo: undefined, dateTo: undefined, periodNum: index + 2 };
              if (keyNum === this.getMonthDay(monthTo)) {
                temp.monthFrom = monthTo + 1 > 12 ? 1 : monthFrom + 1;
                temp.dateFrom = 1;
              } else {
                temp.monthFrom = monthTo;
                temp.dateFrom = keyNum + 1;
              }
              if (data.find(item => item.index === index + 1)) {
                data.map(item => {
                  if (item.index === index + 1) {
                    item = Object.assign(item, temp);
                  }
                  return item;
                });
                data.splice(index + 2, data.length - index - 2);
              } else {
                index + 1 < info.totalPeriodNum && data.push(temp);
              }
              this.props.form.resetFields();
              this.setState({ data });
            }}
          >
            {options}
          </Select>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key12')/*季度*/, dataIndex: 'quarterNum',
      newRender: (value, record, index) => {
        const { data } = this.state;
        return {
          ele: <Select placeholder={messages('common.select')/*请选择*/} onChange={key => {
            data[index].quarterNum = key;
            this.setState({ data });
          }}>
            <Select.Option value="1">1</Select.Option>
            <Select.Option value="2">2</Select.Option>
            <Select.Option value="3">3</Select.Option>
            <Select.Option value="4">4</Select.Option>
          </Select>,
          initialValue: value
        }
      }
    },
    {
      title: messages('finance-5.key13')/*半年度*/, dataIndex: 'halfYearCode',
      newRender: (value, record, index) => {
        const { data } = this.state;
        return {
          ele: <Select placeholder={messages('common.select')/*请选择*/} onChange={key => {
            data[index].halfYearCode = key;
            this.setState({ data });
          }}>
            <Select.Option value="H1">{messages('finance-5.key14')/*上半年 H1*/}</Select.Option>
            <Select.Option value="H2">{messages('finance-5.key15')/*下半年 H2*/}</Select.Option>
          </Select>,
          initialValue: value
        }
      }
    }
  ];

  getMonthDay = month => {
    return new Date(2019, month, 0).getDate()
  };

  getOption = (starIndex, endIndex, isContainer = true) => {
    let end = isContainer ? Number(endIndex) + 1 : Number(endIndex);
    let res = [];
    for (let m = Number(starIndex); m < end; m++ ) {
      res.push(<Select.Option key={m}>{m}</Select.Option>)
    }
    return res;
  };

  getColumns = () => {
    const { isDefined } = this.state, { getFieldDecorator } = this.props.form;
    let editColumns = deepFullCopy(this.columns);
    if (!isDefined) {
      editColumns.map(item => {
        item.render = (value, record, index) => {
          let obj = item.newRender(value, record, index);
          return (
            <Form.Item>
              {getFieldDecorator(`${item.dataIndex}-${index + 1}`, {
                rules: [{ required: true, message: ' ' }],
                initialValue: obj.initialValue
              })(
                obj.ele
              )}
            </Form.Item>
          )
        };
        return item
      })
    }
    this.setState({ columns: editColumns });
  };

  componentWillMount() {
    this.getInfo();
    this.getData();
  };

  getInfo = () => {
    const { id } = this.props.params;
    this.setState({ infoLoading: true });
    periodDefineService.getPeriodInfo(id)
      .then(res => {
        this.setState({ info: res.data });
      })
      .finally(() => {
        this.setState({ infoLoading: false });
      })
  };

  getData = () => {
    const { id } = this.props.params;
    this.setState({ tableLoading: true });
    periodDefineService.getAccountRuleList(id).then(res => {
      this.setState({ data: res.data.length > 0 ? res.data : [{index: 0, periodNum: 1}], isDefined: res.data.length > 0 }, () => {
        this.getColumns();
      });
    }).finally(() => {
      this.setState({ tableLoading: false });
    })
  };

  handleEditInfo = () => {
    const { info } = this.state;
    SlideFrame.open({
      content: PeriodDefineRule,
      title: messages('finance-5.key16')/*会计期间定义*/,
      params: { record: info },
      afterClose: () => this.getInfo()
    }, this);
  };

  createPeriod = () => {
    Modal.confirm({
      title: messages('finance-5.key17')/*创建期间*/,
      content: (
        <Row>
          <div>
            {messages('finance-5.key18')/*创建年度（输入四位数字）*/}：
          </div>
          <Col span={10}>
            <InputNumber
              placeholder={messages('finance-5.key19')/*年度从*/}
              precision={0} max={9999} min={2000} style={{width:'100%'}}
              onChange={value => this.setState({ yearFrom: value })}
            />
          </Col>
          <Col span={10} offset={4}>
            <InputNumber
              placeholder={messages('finance-5.key20')/*年度到*/}
              precision={0} max={9999} min={2000} style={{width:'100%'}}
              onChange={value => this.setState({ yearTo: value })}
            />
          </Col>
        </Row>
      ),
      onOk: this.handleModalOk
    })
  };

  handleModalOk = () => {
    const { yearFrom, yearTo, info } = this.state;
    if ((yearTo - yearFrom) > 4) {
      message.error(messages('finance-5.key21')/*时间跨度不超过5年*/);
      return false;
    }
    periodDefineService.createPeriod({
      periodSetCode: info.periodSetCode, yearFrom, yearTo
    }).then(() => {
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      message.error(`${messages('common.save.filed')/*保存失败*/}， ${e.response.data.message}`)
    })
  };

  clear = () => {
    this.setState({ data: [{ index: 0, periodNum: 1 }] });
  };

  handleSave = () => {
    const { data, info } = this.state;
    data.map(item => Object.assign(item, { periodSetId: info.id, tenantId: info.tenantId }));
    if (data.length !== info.totalPeriodNum) {
      Modal.error({
        title: messages('finance-5.key22')/*期间数量不对*/,
        content: messages('finance-5.key23')/*期间数应该等于 期间总数*/
      });
      return false;
    }
    this.setState({ saveLoading: true });
    periodDefineService.newAccountRule(data).then(() => {
      this.setState({ saveLoading: false });
      message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
      this.getData();
    }).catch(e => {
      this.setState({ saveLoading: false });
      message.error(`${messages('common.save.filed')/*保存失败*/}，${e.response.data.message}`);
    })
  };

  handleDefault = () => {
    const { id } = this.props.params;
    this.setState({ tableLoading: true });
    periodDefineService.defaultRule(id).then(() => {
      this.getData();
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({ tableLoading: false });
    })
  };

  render() {
    const { info, infoLoading, saveLoading, isDefined, data, columns } = this.state;
    return (
      <div className="new-account-rule">
        <Info
          title={messages('finance-5.key24')/*基础信息*/}
          attributes={this.attributes}
          dataSource={info}
          loading={infoLoading}
        >
          <Button type='primary' onClick={this.handleEditInfo}>{messages('common.edit')/*编辑*/}</Button>
        </Info>
        <div style={{ margin: '12px 0'}}>
          <Condition>
            <Condition.If value={isDefined}>
              <Button type='primary' onClick={this.createPeriod}>{messages('finance-5.key25')/*生成期间*/}</Button>
            </Condition.If>
            <Condition.Else>
              <Space>
                <Button type="primary" onClick={this.clear}>{messages('finance-5.key26')/*清空已填写*/}</Button>
                {info.periodSetCode === 'DEFAULT_CAL' && (
                  <Button type="primary" onClick={this.handleDefault}>{messages('finance-5.key27')/*按自然月生成*/}</Button>
                )}
              </Space>
            </Condition.Else>
          </Condition>
        </div>
        <Form style={{ marginBottom: '84px' }}>
          <Table
            columns={columns}
            dataSource={data}
            rowKey='index'
            pagination={false}
            bordered
            size="middle"
          />
        </Form>
        <div className='footer-operate' style={{ left: '200px', background: '#fff', position: 'fixed' }}>
          {!isDefined && <Button type='primary' onClick={this.handleSave} loading={saveLoading}>{messages('common.ok')/*确定*/}</Button>}
          <Button onClick={() => window.history.go(-1)}>{messages('common.back')/*返回*/}</Button>
        </div>
      </div>
    )
  }

}

export default Form.create()(PeriodDefineDetail)
